package com.njtoyo.taxi.admin.handler.rule.online_valuation;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.njtoyo.taxi.admin.handler.rule.online_valuation.domain.RuleDetail;
import com.njtoyo.taxi.admin.handler.rule.online_valuation.domain.TimePeriod;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * @author mdf
 * @title: RuleMatcherHandler
 * @description: TODO
 * @date 2025/3/11 14:19
 */
public class OnlineValuationTimeMatcherHandler {
    /**
     * 匹配符合时间条件的规则
     *
     * @param targetTime 格式：HH:mm
     * @return 匹配的规则列表
     */
    public static Optional<RuleDetail> matchRules(JSONArray jsonArray, String targetTimeStr) {
        String timePart = targetTimeStr.substring(11, 16);
        final LocalTime targetTime = LocalTime.parse(timePart, DateTimeFormatter.ofPattern("HH:mm"));
        List<RuleDetail> rules = JSON.parseArray(jsonArray.toJSONString(), RuleDetail.class);

        return rules.stream()
                .filter(rule -> hasMatchingPeriod(rule, targetTime))
                .findFirst();
    }

    private static boolean hasMatchingPeriod(RuleDetail rule, LocalTime targetTime) {
        List<TimePeriod> periods = JSON.parseArray(rule.getPeriod(), TimePeriod.class);
        return periods.stream().anyMatch(period -> period.contains(targetTime));
    }
}
